<?php

namespace App\Http\Controllers\Coin;

use App\Http\Controllers\Controller;
use App\Models\Version;
use Illuminate\Http\Request;

/**
 * 通用方法
 */
class PublicController extends Controller
{
    /**
     * 获取usdt实时价格（即美元汇率）
     * @author hxq
     */
    public function get_usdt_rate(Request $request)
    {
        //百度获取美元兑人民币汇率
        $get_cur = $this->convertCurrency("USD", "CNY", 1);

        echo $get_cur;
    }

    /**
     * 使用百度搜索获取汇率
     * @author hxq
     * @param  [type] $from   [description]
     * @param  [type] $to     [description]
     * @param  [type] $amount [description]
     * @return [type]         [description]
     */
    private function convertCurrency($from, $to, $amount)
    {
        $data = file_get_contents("http://www.baidu.com/s?wd={$from}%20{$to}&rsv_spt={$amount}");

        preg_match("/<div>1\D*=(\d*\.\d*)\D*<\/div>/", $data, $converted);

        $converted = preg_replace("/[^0-9.]/", "", $converted[1]);

        return number_format(round($converted, 3), 2,'.','');
    }

    /**
     * 谷歌接口获取汇率（需翻墙）
     * @param  [type] $from_Currency [description]
     * @param  [type] $to_Currency   [description]
     * @param  [type] $amount        [description]
     * @return [type]                [description]
     */
    private function currency($from_Currency, $to_Currency, $amount)
    {
        $url = "https://www.google.com/finance/converter?a=" . $amount . "&from=" . $from_Currency . "&to=" . $to_Currency;

        $ch = curl_init();

        $timeout = 0;

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $rawdata = curl_exec($ch);

        curl_close($ch);

        $matches = array();

        preg_match_all("|(.*)|U", $rawdata, $matches);

        $result = explode(" ", $matches[1][0]);

        return round($result[0], 2);
    }

    /**
     * 获取最新发布版本
     * @author hxq
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_last_version(Request $request)
    {
        $type = $request->get('type') ?? 'android';
        //DB::connection()->enableQueryLog();
        $ver = Version::where(['type' => strtolower($type)])->orderBy('created_at', 'desc')->first();
        //dd(DB::getQueryLog());
        if (!$ver) {
            return response()->json(['status' => 0, 'msg' => '没有数据']);
        }
        $data['version']    = $ver->version;
        $data['oss_path']   = $ver->oss_path;
        $data['is_force']   = $ver->is_force;
        $data['note']       = $ver->note;
        $data['type']       = $ver->type;
        $data['created_at'] = $ver->created_at->format('Y-m-d H:i:s');

        return response()->json(['status' => 1, 'msg' => '成功', 'data' => $data]);
    }
}
